<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>welcome</title>
<script type="text/javascript">
	var wsServer = 'ws://192.168.4.34:8080/';
	var websocket;
	var message = {user_id:'',to:'',content:'',is_init:false};
	function connection(){
		var user_id = document.getElementById('user_id').value;
		websocket = new WebSocket(wsServer)
		websocket.onopen = function(event){
			message.user_id = user_id;
			message.is_init = true;
			websocket.send(JSON.stringify(message)); // 似乎只能发送三种数据格式：UTF-8 text data，ArrayBuffers和blobs
			message.is_init = false;
		};
		websocket.onmessage = function(event){
			// data = {user_id:'',to:'',content:'',is_init:''};
			var data = event.data;
			data = JSON.parse(data);
			message.user_id = data.user_id;
			console.log(data);
			if (!data.is_init) {
				var msg = "<p><a>"+message.user_id+"</a>";
				if (data.to) {
					msg += "对你说："+data.content;
				}else {
					msg += "对大家说："+data.content;
				}
				msg += "</p>";	
				document.getElementById('content').innerHTML = document.getElementById('content').innerHTML + msg;	
			};
		};
	}
	function sendMsg(){
		var user_id = document.getElementById('user_id').value;
		var msg = document.getElementById('msg').value;
		var to = document.getElementById('to').value;
		document.getElementById('msg').value = '';
		message.content = msg;
		message.to = to;
		websocket.send(JSON.stringify(message)); 
	}
	function parseSendTo(to_id){
		document.getElementById('to').value = to_id;
	}
</script>
</head>
<body>
<div>
	<input type="text" id="user_id" />
	<input type="button" value="connection" onclick="connection()" />
</div>
<p></p>
<div>
	<div>
		to:<input type="text" id="to" />
		<p></p>
		msg:<input type="text" id="msg" />
		<input type="button" value="send" onclick="sendMsg()" />
	</div>
</div>
<div id="content" style="height:100px"></div>
</body>
</html>